<template>
  <div :style="'height:' + height + 'px'" :ref="'echart_' + name"></div>
</template>
<script>
const echarts = require('echarts')
export default {
  props: {
    name: {
      type: String,
      default: () => {
        return ''
      },
    },
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
    height: {
      type: Number,
      default: () => {
        return 300
      },
    },
    extend: {
      type: Object,
      default: () => {
        return {
          title: '', //标题
          legend: false, //是否显示legend
          radius: ['0%', '60%'], //圆圈比列
        }
      },
    },
  },
  watch: {
    data() {
      this.init()
    },
  },
  methods: {
    init() {
      const chartEl = this.$refs['echart_' + this.name]
      const myChart = echarts.init(chartEl)
      const seriesData = this.data
      const legend = {
        right: '4%',
        data: seriesData.map((item) => item.name),
      }
      const option = {
        title: {
          text: this.extend.title,
          left: '20px',
        },
        grid: {
          left: '20px',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        series: [
          {
            name: '数据名称',
            type: 'pie',
            radius: this.extend.radius,
            center: ['50%', '55%'],
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }
      if (this.extend.legend) {
        option.legend = legend
      }
      myChart.setOption(option)
    },
  },
}
</script>
